package com.controller.space;

import com.domain.*;
import com.server.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(path="/space")
public class spaceController {

    @Resource(name = "userService")
    private UserService userService;
    @Resource(name = "spaceService")
    private SpaceService spaceService;
    @Resource(name = "discussService")
    private DiscussService discussService;
    @Resource(name = "memberService")
    private MemberService memberService;
    @Resource(name = "contributeService")
    private ContributeService contributeService;
    @Resource(name="resourceService")
    private ResourceService resourceService;


    @RequestMapping(value="/{formName}")
    public String f(@PathVariable String formName){
        return formName;
    }

    @RequestMapping(value = "/search")
    public String searchAll(String title,Model model){
        List<Discuss> discuss=discussService.selectDiscussByTitle(title);
        System.out.println("========================================"+discuss);
        List<Resources> res=resourceService.selectResourceByTitle(title);
        System.out.println("========================================"+res);
        model.addAttribute("title",title);
        model.addAttribute("res",res);
        model.addAttribute("discuss",discuss);
        return "space-search";
    }


    @RequestMapping(path = "/spacename")
    public String index(Integer space_id,Integer userId,Integer id,
                         Model model, HttpSession session) {
        Space space=spaceService.selectSpaceByIdAndUserId(space_id,userId);
        String result=memberService.selectMemberByuser_idAndspace_id(id,space_id);
        System.out.println(result);
        model.addAttribute("result",result);
        //计算资源总数：
        int resourceTotal=resourceService.findResourceTotal(space_id);
        session.setAttribute("resourceTotal",resourceTotal);
        //计算话题总数：
        int discussTotal = discussService.findDiscussTotal(space_id);
        session.setAttribute("discussTotal",discussTotal);
        //计算贡献总数：
        int contributeTotal=contributeService.showContributeTotal(space_id);
        session.setAttribute("contributeTotal",contributeTotal);
        //计算成员总数：
        int memberCount=memberService.findMemberTotal(space_id);
        session.setAttribute("memberCount",memberCount);
        //查询该空间的最新话题：
        List discussList=discussService.descCreateDateLimitPageSize(space_id,8);
        //查询该空间的最新资源
        List reList=resourceService.descCreateDate(space_id);
        //显示空间主页管理团队部分：
        int user_id=spaceService.selectUserIdBySpaceId(space_id);
        User user=userService.selectUserById(user_id);
        System.out.println("空间创建者：==="+user);
        model.addAttribute("user",user);
        model.addAttribute("discussList",discussList);
        model.addAttribute("reList",reList);
        model.addAttribute("space",space);
        session.setAttribute("space",space);
        return "space-main";
    }

    @RequestMapping(path = "/spacemember")
    public String spaceMember(Integer userId,String name,Model model,HttpSession session) {
        int memberId=userId;
        List<Space> space=spaceService.selectSpaceByUserId(userId);
        model.addAttribute("space",space);
        User user1=userService.selectUserById(userId);
        model.addAttribute("user1",user1);
        List<Discuss> discuss=discussService.selectDiscussByMemberId(memberId);
        model.addAttribute("discuss",discuss);
        return "/user-dongtai";
    }

    @RequestMapping(value = "/spae-joinspace")
    public String spacejoin(Model model){
        return "space-joinspace";
    }
    @RequestMapping(value = "/space-joinspace",method=RequestMethod.POST)
    public String joinSpace(Member member,Integer space_id,Integer userId,Model model,HttpSession session){
        Space space1=spaceService.selectSpaceById(space_id);
        User user=userService.selectUserById(userId);
        String result=memberService.selectMemberByuser_idAndspace_id(userId,space_id);
        if(result==null) {
            member.setUsername(user.getUsername());
            member.setStatus(1);
            member.setUser_id(userId);
            memberService.insertMember(member);
            //计算资源总数：
            int resourceTotal = resourceService.findResourceTotal(space_id);
            session.setAttribute("resourceTotal", resourceTotal);
            //计算话题总数：
            int discussTotal = discussService.findDiscussTotal(space_id);
            session.setAttribute("discussTotal", discussTotal);
            //计算贡献总数：
            int contributeTotal = contributeService.showContributeTotal(space_id);
            session.setAttribute("contributeTotal", contributeTotal);
            //计算成员总数：
            int memberCount = memberService.findMemberTotal(space_id);
            session.setAttribute("memberCount", memberCount);
            List<Member> memberList = memberService.selectAllMember(space_id);
            model.addAttribute("memberList", memberList);
            model.addAttribute("space1", space1);
            session.setAttribute("space1", space1);
            return "space-member";
        }
        List<Space> space=spaceService.selectSpaceAll();
        System.out.println(space);
        model.addAttribute("space",space);
        int user_id=user.getId();
        List<Member> memberList=memberService.selectMemberByUserId(user_id);
        List<Space> spaceUser=new ArrayList();
        for(Member member1:memberList){
            int space_id1=member1.getSpace_id();
            Space space2=spaceService.selectSpaceById(space_id1);
            spaceUser.add(space2);
        }
        model.addAttribute("spaceUser",spaceUser);
        model.addAttribute("user",user);
        session.setAttribute("user", user);
        return "main";
    }

    @RequestMapping(value = "/new-space")
    public String newSpace(Model model){
        return "space-new-space";
    }
    @RequestMapping(value = "/upload-Image",method=RequestMethod.GET)
    public String uploadimage( MultipartFile file,HttpSession session, Integer userId, Model model,Space space){
        User user=userService.selectUserById(userId);
        space.setUserId(userId);
        space.setStatus(1);
        space.setSpaceHref(0);
        space.setName(" ");
        System.out.println("失败1");
        return "space-new-space";
    }

    @RequestMapping(value = "/new-spaceSubmit",method= RequestMethod.POST)
    public String newSpaceSubmit(MultipartFile file,Space space,Integer userId,Model model,HttpSession session){
        System.out.println("新建空间的用户user_id==="+userId);
        space.setSpaceHref(0);
        space.setStatus(1);
        if(file!=null){
            String spaceLogo=file.getOriginalFilename();
            space.setSpaceimage(spaceLogo);
            //相对路径的图片文件上传：
            String imagepath=session.getServletContext().getRealPath("/WEB-INF/images");
            System.out.println("头像上传相对路径imagepath===="+imagepath);
            File newImage=new File(imagepath+"\\"+spaceLogo);
            System.out.println("********进入判断**********");
            if(!newImage.getParentFile().exists()){
                newImage.getParentFile().mkdirs();
            }
            try {
                file.transferTo(newImage);
                int result1=spaceService.insertSpace(space);
                if(result1<=0){
                    System.out.println("失败2");
                    return "space-new-space";
                }
                //查询出新建空间的用户信息：
                User user=userService.selectUserById(userId);
                model.addAttribute("user",user);
                //查询出该用户的刚刚创建的空间信息：
                Space space1=spaceService.descCreateDateByUserId(userId);
                System.out.println(space1);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println("thread interrupted");
                }
                int space_id=space1.getId();
                //将该用户添加到成员表：
                Member member=new Member();
                member.setUsername(user.getUsername());
                member.setStatus(1);
                member.setUser_id(userId);
                member.setSpace_id(space_id);
                int amount=memberService.insertMember(member);
                System.out.println("向【成员表】中添加了"+amount+"位成员");
                //计算资源总数：
                int resourceTotal = resourceService.findResourceTotal(space_id);
                session.setAttribute("resourceTotal", resourceTotal);
                //计算话题总数：
                int discussTotal = discussService.findDiscussTotal(space_id);
                session.setAttribute("discussTotal", discussTotal);
                //计算贡献总数：
                int contributeTotal = contributeService.showContributeTotal(space_id);
                session.setAttribute("contributeTotal", contributeTotal);
                //计算成员总数：
                int memberCount = memberService.findMemberTotal(space_id);
                session.setAttribute("memberCount", memberCount);
                String result=memberService.selectMemberByuser_idAndspace_id(userId,space_id);
                System.out.println(result);
                model.addAttribute("result",result);

                model.addAttribute("space",space1);
                session.setAttribute("space",space1);
                return "space-main";
            }  catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("131313131313");
        return "space-new-space";
    }

    @RequestMapping(value = "/defaultSpace")
    public String defaultSpace(@RequestParam(value = "id") Integer id,@RequestParam(value = "userId") Integer userId, Model model, HttpSession session){
        User user=userService.selectUserById(userId);
        List<Space> space=spaceService.selectSpaceAll();
        System.out.println(space);
        model.addAttribute("space",space);
        List<Space> spaceUser=spaceService.selectSpaceByUserId(userId);
        model.addAttribute("spaceUser",spaceUser);
        session.setAttribute("user", user);
        model.addAttribute("user",user);
        spaceService.deleteById(id);
        return "main";
    }

    @RequestMapping(value = "/spacePaixu1")
    public String spacePaixu1(@RequestParam(value = "userId") Integer userId,
                @RequestParam(value="page",defaultValue="1") int page,
                @RequestParam(value="pageSize",defaultValue="10") int pageSize,Model model
            , HttpSession session){
        User user=userService.selectUserById(userId);
        List<Space> space=spaceService.selectSpaceAll();
        System.out.println(space);
        model.addAttribute("space",space);
        int user_id=user.getId();
        List<Member> memberList=memberService.selectMemberByUserId(user_id);
        List<Space> spaceUser=new ArrayList();
        for(Member member:memberList){
            int space_id=member.getSpace_id();
            Space space1=spaceService.selectSpaceById(space_id);
            spaceUser.add(space1);
        }
        model.addAttribute("spaceUser",spaceUser);
        System.out.println(spaceUser);
        //分页：
        List<Space> spaceList=spaceService.findAllSpace(page, pageSize);
        model.addAttribute("spaceList",spaceList);
        //计算总页数：
        int spaceTotal=spaceService.findSpaceTotal();
        System.out.println("登陆显示总数为：===="+spaceTotal);
        if((spaceTotal/pageSize)<1){
            model.addAttribute("pageTotal",1);
        }else{
            System.out.println("登陆spaceTotal%pageSize==="+(spaceTotal%pageSize));
            if(spaceTotal%pageSize!=0){
                int pageTotal=new Integer(spaceTotal/pageSize+1);
                model.addAttribute("pageTotal",pageTotal);
            }else{
                int pageTotal=new Integer(spaceTotal/pageSize);
                model.addAttribute("pageTotal",pageTotal);
            }
        }
        //设置当前为第一页：
        model.addAttribute("currentPage",page);
        model.addAttribute("user",user);
        session.setAttribute("user", user);
        return "main";
    }

    @RequestMapping(value = "/spacePaixu2")
    public String spacePaixu(@RequestParam(value = "userId") Integer userId,
                             @RequestParam(value="page",defaultValue="1") int page,
                             @RequestParam(value="pageSize",defaultValue="10") int pageSize,Model model){
        List<Space> space=spaceService.descCreateDate();
        model.addAttribute("space",space);
        int user_id=userId;
        List<Member> memberList=memberService.descCreateDateByUserId(user_id);
        List<Space> spaceUser=new ArrayList();
        for(Member member:memberList){
            int space_id=member.getSpace_id();
            Space space1=spaceService.selectSpaceById(space_id);
            spaceUser.add(space1);
        }
        model.addAttribute("spaceUser",spaceUser);
        System.out.println(spaceUser);
        //分页：
        List<Space> spaceList=spaceService.findAllSpace(page, pageSize);
        model.addAttribute("spaceList",spaceList);
        //计算总页数：
        int spaceTotal=spaceService.findSpaceTotal();
        System.out.println("登陆显示总数为：===="+spaceTotal);
        if((spaceTotal/pageSize)<1){
            model.addAttribute("pageTotal",1);
        }else{
            System.out.println("登陆spaceTotal%pageSize==="+(spaceTotal%pageSize));
            if(spaceTotal%pageSize!=0){
                int pageTotal=new Integer(spaceTotal/pageSize+1);
                model.addAttribute("pageTotal",pageTotal);
            }else{
                int pageTotal=new Integer(spaceTotal/pageSize);
                model.addAttribute("pageTotal",pageTotal);
            }
        }
        //设置当前为第一页：
        model.addAttribute("currentPage",page);
        return "main";
    }

    @RequestMapping(value = "/space-manageForm1",method=RequestMethod.POST)
    public String manageForm1(MultipartFile file,@RequestParam("id")Integer id,@RequestParam("name")String name,
                              @RequestParam("detail")String detail,HttpSession session,Model model){
        Space space1=spaceService.selectSpaceById(id);
        space1.setName(name);
        space1.setDetail(detail);
        spaceService.updateSpaceById(space1);
        if(file.getName()!=""){
            String spaceimage=file.getOriginalFilename();
            //spaceimage=spaceimage.substring(0,spaceimage.lastIndexOf("."));
            System.out.println(spaceimage);
            space1.setSpaceimage(spaceimage);
            String imagepath="D:/idea/learner/src/main/webapp/WEB-INF/images";
            File newImage=new File(imagepath+"\\"+spaceimage);
            if(!newImage.getParentFile().exists()){
                newImage.getParentFile().mkdirs();
            }
            try {
                file.transferTo(newImage);
                int result=spaceService.updateSpaceById(space1);
                space1.setName(name);
                space1.setDetail(detail);
                spaceService.updateSpaceById(space1);
                Space space=spaceService.selectSpaceById(id);
                session.setAttribute("space",space);
                if(result<=0){
                    System.out.println("上传失败2！");
                    return "space-manage";
                }
                return "space-manage";
            }  catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        Space space=spaceService.selectSpaceById(id);
        session.setAttribute("space",space);
        return "space-manage";
    }

    @RequestMapping(value = "/space-manageForm2")
    public String manageForm2(@RequestParam("id")Integer id,@RequestParam("status") Integer status,
                              HttpSession session,Model mmodel){
        Space space=spaceService.selectSpaceById(id);
        space.setStatus(status);
        spaceService.updateSpaceById(space);
        session.setAttribute("space",space);
        return "space-manage";
    }

    @RequestMapping(value = "/space-delete")
    public String spaceDelete(@RequestParam("id")Integer id,@RequestParam("userId")Integer userId,
                              @RequestParam(value="page",defaultValue="1") int page,
                              @RequestParam(value="pageSize",defaultValue="10") int pageSize,HttpSession session,Model model){
        spaceService.deleteById(id);
        User user=userService.selectUserById(userId);
        List<Space> space=spaceService.selectSpaceAll();
        System.out.println(space);
        model.addAttribute("space",space);
        int user_id=user.getId();
        List<Member> memberList=memberService.selectMemberByUserId(user_id);
        List<Space> spaceUser=new ArrayList();
        for(Member member:memberList){
            int space_id=member.getSpace_id();
            Space space1=spaceService.selectSpaceById(space_id);
            spaceUser.add(space1);
        }
        model.addAttribute("spaceUser",spaceUser);
        //分页：
        List<Space> spaceList=spaceService.findAllSpace(page, pageSize);
        model.addAttribute("spaceList",spaceList);
        //计算总页数：
        int spaceTotal=spaceService.findSpaceTotal();
        System.out.println("登陆显示总数为：===="+spaceTotal);
        if((spaceTotal/pageSize)<1){
            model.addAttribute("pageTotal",1);
        }else{
            System.out.println("登陆spaceTotal%pageSize==="+(spaceTotal%pageSize));
            if(spaceTotal%pageSize!=0){
                int pageTotal=new Integer(spaceTotal/pageSize+1);
                model.addAttribute("pageTotal",pageTotal);
            }else{
                int pageTotal=new Integer(spaceTotal/pageSize);
                model.addAttribute("pageTotal",pageTotal);
            }
        }
        //设置当前为第一页：
        model.addAttribute("currentPage",page);
        session.setAttribute("user", user);
        model.addAttribute("user",user);
        return "main";
    }

    @RequestMapping(value = "/space-tuichu")
    public String spaceTuichu(Integer id,Integer space_id,
                              @RequestParam(value="page",defaultValue="1") int page,
                              @RequestParam(value="pageSize",defaultValue="10") int pageSize,Model model){
        //查询空间创建者id：
        int space_firstUser=spaceService.selectUserIdBySpaceId(space_id);
        //判断退出空间的是创建者还是成员：
        if(space_firstUser!=id){
            int i=memberService.deleteById(space_id,id);
            System.out.println("有"+i+"位成员退出该空间");
        }else{
            System.out.println("id=="+space_firstUser+"创建者退出空间");
            int i=memberService.deleteAllMemberBySpaceId(space_id);
            System.out.println("共删除空间id为=="+space_id+"的"+i+"位成员们");
            int count=spaceService.deleteByUserId(id,space_id);
            System.out.println("删除"+count+"条空间记录");
        }
        //删除该空间的信息：
        resourceService.deleteResourceBySpaceId(space_id);
        discussService.deleteDiscussBySpaceId(space_id);
        contributeService.deleteContributeBySpaceId(space_id);
        User user=userService.selectUserById(id);
        List<Space> space=spaceService.selectSpaceAll();
        System.out.println(space);
        model.addAttribute("space",space);
        int user_id=user.getId();
        List<Member> memberList=memberService.selectMemberByUserId(user_id);
        List<Space> spaceUser=new ArrayList();
        for(Member member:memberList){
            int space_id1=member.getSpace_id();
            Space space1=spaceService.selectSpaceById(space_id1);
            spaceUser.add(space1);
        }
        model.addAttribute("spaceUser",spaceUser);
        //分页：
        List<Space> spaceList=spaceService.findAllSpace(page, pageSize);
        model.addAttribute("spaceList",spaceList);
        //计算总页数：
        int spaceTotal=spaceService.findSpaceTotal();
        System.out.println("登陆显示总数为：===="+spaceTotal);
        if((spaceTotal/pageSize)<1){
            model.addAttribute("pageTotal",1);
        }else{
            System.out.println("登陆spaceTotal%pageSize==="+(spaceTotal%pageSize));
            if(spaceTotal%pageSize!=0){
                int pageTotal=new Integer(spaceTotal/pageSize+1);
                model.addAttribute("pageTotal",pageTotal);
            }else{
                int pageTotal=new Integer(spaceTotal/pageSize);
                model.addAttribute("pageTotal",pageTotal);
            }
        }
        //设置当前为第一页：
        model.addAttribute("currentPage",page);
        model.addAttribute("user",user);
        return "main";
    }

}